from system.object import Object
from system.eventServer import eventServer

class TextBox(Object):
    def __init__(self, parent, type = None, name = None):
        Object.__init__(self, parent, type, name)
        
        self.defaultVar("renderOp2d","rect")
        self.defaultVar("color",(0,0,0))
        self.defaultVar("hasFocus",False)
        self.defaultVar("text","")
        
        self.outline = self.addChild("outline")
        self.outline.setVar("renderOp2d","rect")
        self.outline.setVar("filled",False)
        self.outline.setVar("color",(0.5,0.5,0.5))
        
        self.text = self.addChild("text")
        self.text.setVar("renderOp2d","text")
        self.text.setVar("text",self.getVar("text"))
        self.text.setVar("color",(1,1,1))
        self.text.setVar("align","center")
        self.text.setVar("pos",(0,0.9))
        
        eventServer.register("objectClickDown",self.objectClickDown)
        eventServer.register("keyDown",self.keyDown)
        
        self.selectClick = None
        
    def objectClickDown(self, cmd, args):
        if args['path'] == self.getVar("path"):
            self.setVar("hasFocus",True)
            self.outline.setVar("color",(1,1,1))
            self.selectClick = args['count']
        elif self.selectClick != args['count']:
            self.setVar("hasFocus",False)
            self.outline.setVar("color",(0.5,0.5,0.5))
            
    def keyDown(self, cmd, args):
        if self.getVar("hasFocus"):
            if args['keyName'] == 'backspace' and self.text.getVar("text"):
                self.text.setVar("text",self.text.getVar("text")[:-1])
                
            elif args['keyName'] == 'return':
                if self.hasVar("returnEvent"):
                    msgArgs = {"text":self.text.getVar("text")}
                    if self.hasVar("returnArgs"):
                        msgArgs.update(self.getVar("returnArgs"))
                    eventServer.pull(self.getVar("returnEvent"),msgArgs)
                    
            elif args['keyChar']:
                self.text.setVar("text",self.text.getVar("text") + args['keyChar'])
                
            if not self.text.getVar("text").isalnum():
                self.text.setVar("text","")
                
            self.setVar("text",self.text.getVar("text"))
